#!/usr/bin/perl 

#use warnings;
use strict;

open(STUPID, "<", "stupid_array.txt") or
	die "Stupid file stupid_array.txt couldn't be opened. Reason: $!";

my @less_stupid_array;
my @ok_array;
my @smart_array;

my $i = 0;
while(<STUPID>)
	{
		next if(m/\{$/ || m/=$/ || m/\;/ || m/^\n/);
 
		#print $_;	# Debug debug
		s/\{//;
		s/\}//;
		s/\n//;
		s/\t//;
		s/\;/\}\;\n/;
		$less_stupid_array[$i] = $_;
		#print $less_stupid_array[$i]."\n"; # Debug debug
		$i++;
	}
	
# Ok, array populated

foreach (@less_stupid_array) {
	#s/,\n/,\ /;
	s/\ //g;

	push(@ok_array, split(",")); 
	push(@ok_array, "0");	# We pad an extra zero element to get 26 rows -> 13 full bytes
							# the 26th row / last half of 13th byte is discarded anyway later
	} 


my $column = 1;
my $first_half = 1;
my $half_counter=0;
my $smart_counter = 0;

#print "We now got the 4bit values, stored in a byte each....\n\n\n";
for (my $i = 0; $i < @ok_array; $i++) {	# Here we got the 4bit values, stored in one byte each

		# Print it out for debugging
		print "0" if ($ok_array[$i] < 10);
		print $ok_array[$i]." ";
		
		
		$column++;
		print ("\n") if ($column == 27);
		$column = 1 if ($column > 26);
		
		$first_half = 1;# THIS MIGHT CAUSE THE PROBLEM - ORIGINALLY 1
		$first_half = 0 if($half_counter==1);
		
		# Time to truncate it into bytes
		# When we're on 
		if($first_half) { 	# We're getting the 4 most significant bits - first half of the byte
			$smart_array[$smart_counter] = $ok_array[$i+1] << 4 | $ok_array[$i];
			$smart_counter++;
			} else {		# We're on the second half, so we skip quietly
			}

		$half_counter++;
		$half_counter=0 if($half_counter ==2);
	}


my $x = 0;
my $y = 0;
print "\nPROGMEM uint8_t image1[13*25] =	// 13*25 = 325	// Saved in program (flash) memory to save RAM\n";
print "\t{\n\t";

foreach(@smart_array) {
	
	#print "0" if ($_ <10);		# Debug debug
	#print "0" if ($_ <100);	# Debug debug
	print $_;
	print "," unless($y == 324);
	print " " unless($x == 12);
	$x++;
	$y++;
	if ($x == 13) {
		$x = 0;
		print "\n\t";
		}
	}

print "\}\;\n\nOk, done! Converted $x columns and $y rows.\n";